let websocket: WebSocket | null = null;

export const WS_URL = "ws://localhost:8080";
export function createWebSocket(token: string) {
  websocket = new WebSocket(`ws://${WS_URL}?token=${token}`);

  websocket.onopen = () => {
    console.log("WebSocket 连接成功");
  };

  websocket.onerror = (error) => {
    console.error("WebSocket 连接错误:", error);
  };

  websocket.onclose = () => {
    console.log("WebSocket 连接已关闭");
  };
}

export function sendWebSocketMessage(message: any) {
  if (websocket && websocket.readyState === WebSocket.OPEN) {
    websocket.send(JSON.stringify(message));
  } else {
    console.error("WebSocket 未连接，无法发送消息");
  }
}

export function onWebSocketMessage(callback: (data: any) => void) {
  if (websocket) {
    websocket.onmessage = (event) => {
      const data = JSON.parse(event.data);
      callback(data);
    };
  }
}

export function closeWebSocket() {
  if (websocket) {
    websocket.close();
  }
}
